package com.msc.mc.httpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;



/**
 * http request util
 *
 * @author sdmadm
 *
 */
public class HttpClient   extends Thread {

        
        //----------------------------------------------------------------------->
        // Joo 
        private static int port = -1 ;
        private static String serviceUrl = null;
        
        private static boolean isHostConnectable(String host, int port) {
            Socket socket = new Socket();
            try {
                socket.connect(new InetSocketAddress(host, port));
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return true;
        }
        
        /**
         * get webservice port
         * @return
         */
        public static int getPort() {
        	if( port == -1 ) {
        		port = isHostConnectable( "127.0.0.1" , 8181) ? 8181 : 8989 ; 
        	}
        	return port;
        }
        
        public static String getServiceUrl() {
        	if( serviceUrl == null ) {
	        	//String path = "com/msc/mc/httpClient/";
	        	//serviceUrl = PropertiesUtil.readPropertiesByGetSourceAsStream(path+"httpClient.properties", "url");
	        	serviceUrl = "http://127.0.0.1:"+ getPort() + "/MCWeb/notice";
        	}
        	return serviceUrl ;
        }
        //------------------------------------------------------------------------<
        public HttpClient() {

        }
        private String sbParams ;
        public HttpClient(String sbParams) {
                this.sbParams = sbParams;
        }

        public void run() {
                try {
                        sendPost(sbParams);
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }



        public static void main(String [] args) throws Exception {
               // new HttpClient().sendPost("?subid=123123123");
        	boolean bool  = isHostConnectable( "127.0.0.1" , 8989 );
        	System.out.println( bool );
        }
        /**
         *  send http reqest , request  method  post
         * @param urlParam   request  url address
         * @param sbParams   request  params
         * @param charset
         * @return  response message
         */
        public String sendPost(  String sbParams ) throws Exception{
        		//--------------------------------------------------------->
        		//Joo 
        		//--------------------------------------------------------->
        		//String path = "com/msc/mc/httpClient/";
                //String  urlParam = PropertiesUtil.readPropertiesByGetSourceAsStream(path+"httpClient.properties", "url");
                //String charset 	 = PropertiesUtil.readPropertiesByGetSourceAsStream(path+"httpClient.properties", "charset");
        		String urlParam = getServiceUrl();
        		String charset  = "utf-8" ;
        		//---------------------------------------------------------<
        		
        		StringBuffer resultBuffer = null;
                System.out.println("" + urlParam);
                sbParams += "&key=212";

                // 构建请求参数s
                /*
                 * StringBuffer sbParams = new StringBuffer(); if (params != null &&
                 * params.size() > 0) { for (Entry<String, Object> e : params.entrySet()) {
                 * sbParams.append(e.getKey()); sbParams.append("=");
                 * sbParams.append(e.getValue()); sbParams.append("&"); } }
                 */
                HttpURLConnection con = null;
                OutputStreamWriter osw = null;
                BufferedReader br = null;
                // 发送请求
                try {
                        URL url = new URL(urlParam);
                        con = (HttpURLConnection) url.openConnection();
                        con.setRequestMethod("POST");
                        con.setDoOutput(true);
                        con.setDoInput(true);
                        con.setUseCaches(false);
                        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                        if (sbParams != null && sbParams.length() > 0) {
                                osw = new OutputStreamWriter(con.getOutputStream(), charset);
                                osw.write(sbParams.substring(0, sbParams.length() - 1));
                                osw.flush();
                        }
                        // 读取返回内容
                        resultBuffer = new StringBuffer();
//                      if (contentLength > 0) {
                      try {
                          br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
                          String temp;
                          while ((temp = br.readLine()) != null) {
                                  resultBuffer.append(temp);
                          }
                      }catch(Exception ex) {
                      	ex.printStackTrace();
                      }
//                      }
                      
                      
                      System.out.println("----------------------->>>>>>>>  resultBuffer:" + resultBuffer.toString());
                } catch (Exception e) {
                        e.printStackTrace();
                        throw new RuntimeException(e);
                } finally {
                        close(con,osw,br);
                }

                return resultBuffer.toString();
        }


        /**
         * close http request connection
         * @param con   http request connection
         * @param osw   output stream writer
         * @param br
         */
        private void close(HttpURLConnection con,OutputStreamWriter osw,BufferedReader br) {
                if (osw != null) {
                        try {
                                osw.close();
                        } catch (IOException e) {
                                osw = null;
                                throw new RuntimeException(e);
                        } finally {
                                if (con != null) {
                                        con.disconnect();
                                        con = null;
                                }
                        }
                }
                if (br != null) {
                        try {
                                br.close();
                        } catch (IOException e) {
                                br = null;
                                throw new RuntimeException(e);
                        } finally {
                                if (con != null) {
                                        con.disconnect();
                                        con = null;
                                }
                        }
                }
        }

}
